package org.lex.dbq.view.sql.result;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import org.eclipse.jface.action.ToolBarManager;
import org.eclipse.swt.SWT;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.TableColumn;
import org.eclipse.swt.widgets.ToolBar;
import org.lex.dbq.model.jdbc.resultset.IResultSetFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class TableResultViewer extends ResultSetViewer {
	Table table = null;
	List<TableColumn> columns = new ArrayList<TableColumn>();

	private Label statusLabel = null;
	private Logger log = LoggerFactory.getLogger(TableResultViewer.class);

	public TableResultViewer(Composite parent, int style) {
		super(parent, style);
		this.initialize();
	}

	@Override
	public void setResultSet(IResultSetFactory rs) {
		this.result = rs;
		int rowCount = -1;
		long start = System.currentTimeMillis();
		try {
			rowCount = new ResultSetHelper().fill(this, rs.execute());
		} catch (SQLException e) {
			log.error("read result failed", e);
		}
		StringBuilder buf = new StringBuilder();
		if (-1 != rowCount) {
			buf.append(rowCount).append(" rows in ");
		}
		buf.append(((float) (System.currentTimeMillis() - start)) / 1000);
		buf.append(" seconds");
		statusLabel.setText(buf.toString());
	}

	private void initialize() {
		GridLayout layout = new GridLayout();
		layout.numColumns = 1;
		layout.makeColumnsEqualWidth = false;
		layout.marginWidth = 0;
		layout.marginHeight = 0;

		this.setLayout(layout);

		this.createToolBar(this);
		this.createTable(this);
		this.createStatusBar(this);
	}

	private void createToolBar(Composite parent) {
		GridData d = new GridData(GridData.FILL_HORIZONTAL);

		ToolBar tb = new ToolBar(parent, SWT.FLAT);
		tb.setLayoutData(d);

		ToolBarManager toolbar = new ToolBarManager(tb);
		toolbar.add(new ExportHtmlAction(this));
		toolbar.update(true);
	}

	private void createTable(Composite parent) {
		GridData d = new GridData(GridData.FILL_BOTH);
		d.verticalSpan = 1;
		d.horizontalSpan = 1;

		table = new Table(this, SWT.FULL_SELECTION | SWT.BORDER);
		table.setHeaderVisible(true);
		table.setLinesVisible(true);
		table.setLayoutData(d);
	}

	private void createStatusBar(Composite parent) {
		GridData d = new GridData(GridData.FILL_HORIZONTAL);
		d.verticalSpan = 1;
		d.horizontalSpan = 1;

		statusLabel = new Label(parent, SWT.NONE);
		statusLabel.setLayoutData(d);
		statusLabel.setText("OK");
	}
}
